package com.nwpu.vote.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nwpu.vote.model.*;
import com.nwpu.vote.util.*;
import com.nwpu.vote.control.*;
import com.nwpu.vote.parser.*;

public class UserCreateServlet extends HttpServlet {
	
	private static java.util.logging.Logger logger = Logger.getLogger(UserCreateServlet.class.getName());
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			VoteUser user = new UserParser().parse(req);
			
			//save the vote to Google data store
			VotePersistentImpl.instance.save(user);
			
			resp.setStatus(200);
			req.getRequestDispatcher("/newusersuccess.html").forward(req, resp);
			resp.setContentType("text/plain;charset=utf-8");
			PrintWriter pw = resp.getWriter();
			pw.write("the user is created successfully");
			
		} catch (InvalidNewUserException e) {
			resp.setStatus(200);
			PrintWriter pw = resp.getWriter();
			pw.write("Exception:"+e.getMessage());
			e.printStackTrace(pw);
			
			logger.log(Level.FINE, e.getMessage(),e);
		} catch (PersistentException e) {
			resp.setStatus(200);
			PrintWriter pw = resp.getWriter();
			pw.write("Exception:"+e.getMessage());
			e.printStackTrace(pw);
			
			logger.log(Level.FINE, e.getMessage(),e);
		} 
		
	}
}
